<template>
  <Page title="语文作文练习">
    <template #navBarCustom>
      <div class="nav-bar-btns flex">
        <div class="item flex items-center" @click="goToRecords">
          <img class="icon mt-2px mr-6px" src="static/icons/record.png" mode="" />
          <span class="name text-white">练习记录</span>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <div
          class="container w-full h-full bg-white flex flex-col overflow-hidden p-20px box-border"
        >
          <div class="main flex-1 overflow-scroll">
            <!-- 作文标题 -->
            <div class="title-wrap">
              <span class="text-333">作文标题：</span>
              <el-input
                v-model="title"
                placeholder="请输入标题"
                type="text"
                size="large"
                class="input"
              />
            </div>
            <!-- 上传图片 -->
            <div class="upload-wrap">
              <div class="text-333 mt-20px">请拍照上传作文，最多10张照片，请按照顺序依次上传</div>
              <div class="list-wrap mt-25px">
                <div class="inline-block relative" v-for="(img, index) in imgList" :key="index">
                  <el-image :src="img" :preview-src-list="[img]" fit="cover" />
                  <img
                    class="clear absolute"
                    src="static/icons/close-warning.png"
                    :data-index="index"
                    @click="clearImage"
                  />
                </div>
                <img src="static/icons/camera-square.png" @click="upload" />
              </div>
            </div>
          </div>
          <!-- 提交 -->
          <div class="mt-20px flex-center">
            <CustomButton class="block" style="width: 2rem" @click="submit">提交</CustomButton>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page'
import CustomButton from '@/components/button'
import { uploadImage } from '@/utils'
import { correctChineseApi } from '@/api/correct/chinese'
import { MODULE_ID } from '@/store/modules/module-use'

export default {
  components: {
    Page,
    CustomButton
  },
  data() {
    return {
      title: '', // 作文标题
      imgList: [] // 上传的图片列表
    }
  },
  computed: {},
  created() {},
  mounted() {
    // 初始化模块使用记录
    this.$store.commit('setCurrentModuleUse', {
      vm: this._self,
      type: MODULE_ID.CORRECT_CHINESE,
      subjectId: ''
    })
  },
  methods: {
    async upload() {
      if (this.imgList.length === 10) {
        this.$message.info('最多上传10张照片')
        return
      }

      const { android_call } = window

      if (!android_call) {
        const base64 = await uploadImage()
        this.imgList.push(base64)
      } else {
        const callback = (base64) => {
          this.imgList.push(`data:image/png;base64,${base64}`)
          this.$message.success('上传成功！')
        }

        const callBackName = `fn${new Date().getTime()}`
        window.android_call[callBackName] = callback.bind(this)

        android.takePhoto(callBackName)
      }
    },
    clearImage(e) {
      const { index } = e.target.dataset
      this.imgList.splice(parseInt(index), 1)
    },
    async submit() {
      const { title: answer_title, imgList } = this
      const answer_base64 = imgList.map((img) => img.replace('data:image/png;base64,', ''))

      if (!answer_title) {
        this.$message.error('请输入作文标题')
        return
      }

      if (!answer_base64.length) {
        this.$message.error('请拍照上传作文')
        return
      }

      const loading = this.$loading({
        lock: true,
        text: '提交中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      // 一分钟内提交不成功关闭loading弹窗
      const timer = setTimeout(() => {
        loading.close()
      }, 60000)

      const {
        code,
        data: answer,
        msg
      } = await correctChineseApi({
        answer_title,
        answer_base64
      })
      clearTimeout(timer)
      loading.close()

      if (code === 0) {
        this.$route.params.answer_base64 = imgList
        this.$route.params.answer = answer
        this.$router.push('/pages/correct/chinese/result')
      } else {
        this.$message.error(`提交失败 msg:${msg}`)
      }
    },
    goToRecords() {
      this.$router.push('/pages/correct/chinese/record')
    }
  }
}
</script>

<style lang="scss" scoped>
.nav-bar-btns {
  .item {
    height: 30px;
    .icon {
      width: 22px;
      height: 22px;
    }

    .name {
      font-size: 22px;
      line-height: 22px;
    }
  }
}

.container {
  border-radius: 16px;

  .title-wrap {
    font-size: 18px;

    .input {
      width: 570px;
      height: 44px;
    }
  }

  .upload-wrap {
    font-size: 18px;

    .list-wrap {
      display: inline-grid;
      grid-template-columns: 130.625px 130.625px 130.625px 130.625px 130.625px 130.625px 130.625px 130.625px;
      grid-column-gap: 20px;
      grid-row-gap: 20px;

      /deep/ img {
        width: 130.625px;
        height: 130.625px;
      }

      .clear {
        width: 30px;
        height: 30px;
        top: -15px;
        right: -15px;
      }
    }
  }
}
</style>
